package com.hao.demo1;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

/**
 * callable优势：
 * 可以定义返回值
 * 可以抛出异常
 */
public class TestThread5 implements Callable<Boolean> {
    private String url; // 地址
    private String name; // 保存的文件名
    public TestThread5(String url, String name) {
        this.url = url;
        this.name = name;
    }

    public TestThread5() {
    }
    // 下载文件的执行体
    @Override
    public Boolean call() {
        WebDownloader1 webDownloader1 = new WebDownloader1();
        webDownloader1.downloader(url,name);
        System.out.println("下载了文件"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestThread5 t1 = new TestThread5("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片1.jpg");
        TestThread5 t2 = new TestThread5("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片2.jpg");
        TestThread5 t3 = new TestThread5("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fsafe-img.xhscdn.com%2Fbw1%2Fea7faa06-0304-474a-aa3d-68cf0a7c0aa4%3FimageView2%2F2%2Fw%2F1080%2Fformat%2Fjpg&refer=http%3A%2F%2Fsafe-img.xhscdn.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1689238185&t=c3b5466b3e7a9c785bc1ed59466fef37","世浩下载的图片3.jpg");

        // 创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        // 提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        // 获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        System.out.println("rs1------>"+rs1);
        System.out.println("rs2------>"+rs2);
        System.out.println("rs3------>"+rs3);
        // 关闭服务
        ser.shutdown();
    }
}

// 下载器
class WebDownloader1{
    // 下载方法
    public void downloader(String url,String name)  {

        try {
            FileUtils.copyURLToFile(new URL(url),new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader出问题了");
        }
    }
}
